package com.pansoft.openplanet.util;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.common.BaseRequestManager;
import com.efounder.constant.EnvironmentVariable;

import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Response;

/**
 * 网络请求类
 * Created by will on 18-3-21.
 */

public class TCRequestUtil {

    public static final String BASE_URL = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver";

    /**
     * 支付
     */
    public static final String START_PAY_URL = BASE_URL + "/mallOrder/v1/startMallCharge";

    /**
     * 获取充值兑换比例： tcserver/mallOrder/getRateByCardId   参数 cardId
     */
    public static final String RATE_BY_CARDID = "/mallOrder/v1/getRateByCardId";

    /**
     * 通用get请求
     *
     * @param tag       tag
     * @param method    url: 传入"path/method"
     * @param paramsMap 参数
     * @param callback  callback
     */
    public static void getCommonRequest(final String tag, final String method, final HashMap<String, String> paramsMap, final TCRequestCallback callback) {
        JFCommonRequestManager.getInstance()
                .requestGetByAsyn(tag, BASE_URL + "/" + method,
                        paramsMap, new BaseRequestManager.ReqCodeCallBack<String>() {
                            @Override
                            public void onReqFailed(int errorCode, String errorMsg) {
                                if (callback == null) {
                                    return;
                                }
                                if (errorCode == 400) {
                                    callback.onFail("TokenExpireLogOut");
                                    return;
                                }
                                callback.onFail(errorMsg);
                            }

                            @Override
                            public void onReqSuccess(String result) {
                                try {
                                    JSONObject jsonObject = new JSONObject(result);
                                    if (jsonObject.has("error_description") &&
                                            jsonObject.optString("error_description").equals("refreshToken not exists")) {
                                        callback.onFail("TokenExpireLogOut");
                                        return;
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                callback.onSuccess(result);
                            }

                            @Override
                            public void onReqFailed(String errorMsg) {
                            }
                        });
    }

    /**
     * 通用post方法请求
     *
     * @param tag       class name
     * @param method    url: 传入"path/method"
     * @param paramsMap 参数
     * @param callback  callback
     */
    public static void postCommonRequest(final String tag, String method, HashMap<String, String> paramsMap, final TCRequestCallback callback) {
        JFCommonRequestManager.getInstance().requestPostByAsyn(tag,
                BASE_URL + "/" + method, paramsMap, new BaseRequestManager.ReqCodeCallBack<String>() {
                    @Override
                    public void onReqFailed(int errorCode, String errorMsg) {
                        if (callback == null) {
                            return;
                        }
                        if (errorCode == 400) {
                            callback.onFail("TokenExpireLogOut");
                            return;
                        }
                        callback.onFail(errorMsg);
                    }

                    @Override
                    public void onReqSuccess(String result) {
                        if (callback != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.has("error_description") &&
                                        jsonObject.optString("error_description").equals("refreshToken not exists")) {
                                    callback.onFail("TokenExpireLogOut");
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            callback.onSuccess(result);
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                    }
                });
    }


    /**
     * OAuth的get请求方法：请求失败，判断需要获取access_token时调用getTokenRequest方法，成功后再次调用原请求
     *
     * @param tag      tag
     * @param method   url: 传入"path/method"
     * @param params   参数
     * @param callback callback
     */
    public static void getOAuthRequest(final String tag, final String method, final HashMap<String, String> params, final TCRequestCallback callback) {
        getCommonRequest(tag, method, params, callback);

    }

    /**
     * OAuth的post请求方法：请求失败，判断需要获取access_token时调用getTokenRequest方法，成功后再次调用原请求
     *
     * @param tag      tag
     * @param method   url: 传入"path/method"
     * @param params   参数
     * @param callback callback
     */
    public static void postOAuthRequest(final String tag, final String method, final HashMap<String, String> params, final TCRequestCallback callback) {
        postCommonRequest(tag, method, params, callback);
    }

    //重新刷新token(这个方法是反射调用的，别删。。)
    public static void refreshToken(String tag, final TCRequestCallback callback) {
        HashMap<String, String> map = new HashMap<>();
        map.put("grant_type", "refresh_token");
        map.put("client_id", "a6f23fbb-0a1d-4e10-be7e-89181cdf089c");
        map.put("client_secret", "2a6a9640-9a46-4622-b226-bc94b852848c");
        map.put("passwordType", "password");
        map.put("username", EnvironmentVariable.getUserName());
        map.put("password", EnvironmentVariable.getPassword());
        map.put("refresh_token", EnvironmentVariable.getProperty("tc_refresh_token"));
        postCommonRequest(tag, "oauth/accessToken", map, new TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("access_token")) {
                        String newAccessToken = jsonObject.getString("access_token");
                        String newRefreshToken = jsonObject.getString("refresh_token");
                        //请求token成功，将token保存在EV中
                        EnvironmentVariable.setProperty("tc_access_token", newAccessToken);
                        EnvironmentVariable.setProperty("tc_refresh_token", newRefreshToken);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callback != null) {
                    callback.onSuccess(response);
                }
            }

            @Override
            public void onFail(String error) {
                if (callback != null) {
                    callback.onFail(error);
                }
            }
        });
    }

    /**
     * IPComTokenRefresh通过反射调用刷新
     *
     * @param tag tag
     * @return token
     */
    public static Response refreshAccessTokenSync(String tag) {
        HashMap<String, String> map = new HashMap<>();
        map.put("grant_type", "refresh_token");
        map.put("client_id", "a6f23fbb-0a1d-4e10-be7e-89181cdf089c");
        map.put("client_secret", "2a6a9640-9a46-4622-b226-bc94b852848c");
        map.put("passwordType", "password");
        map.put("username", EnvironmentVariable.getUserName());
        map.put("password", EnvironmentVariable.getPassword());
        map.put("refresh_token", EnvironmentVariable.getProperty("tc_refresh_token"));
        return JFCommonRequestManager.getInstance()
                .requestPostBySyn(tag, BASE_URL + "/oauth/accessToken",
                        map);
    }

    public interface TCRequestCallback {

        void onSuccess(String response);

        void onFail(String error);
    }
}